﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class ResLoader : MonoBehaviour
{

#if UNITY_STANDALONE_WIN || UNITY_EDITOR  
	public static readonly string prefix = "file:///";  
#elif UNITY_ANDROID  
	public static readonly string prefix = "jar:file://";
#elif UNITY_IPHONE  
	public static readonly string prefix = "";  

#else
	public static readonly string prefix = ""
#endif  


	public static bool IsHttpUrl(string url)
	{
		if (url.StartsWith ("http://") || url.StartsWith ("https://") || url.StartsWith ("ftp://"))
			return true;

		return false;
	}

	// 网络文件对应本地目录
	public static string Url2LocalPath( string httpUrl )
	{
		int idx = httpUrl.IndexOf ('/', 8);
		string res = httpUrl.Substring (idx);
		string path = Application.persistentDataPath + res;
		return path;
	}

	// 是否已经下载过了
	// ex : https://www.dope.ren/feizhougu/001/01_part1.mp4
	public static bool HaveDownload( string path )
	{

		// 本地文件
		if (IsHttpUrl (path) == false) {
			return true;
		}

		string file = Url2LocalPath (path);

		if (File.Exists (file))
			return true;
		else
			return false;

	}

	class DLData
	{
		public string url = "";
		public Action<float> progressCallback = null;
		public Action<WWW> finishCallback = null;
		public string savePath = "";

		public DLData(string Url, Action<float> ProgressCallback, Action<WWW> FinishCallback, string SavePath)
		{
			url = Url;
			progressCallback = ProgressCallback;
			finishCallback = FinishCallback;
			savePath = SavePath;
		}
	}
	private static List<DLData> urls = new List<DLData> ();


	void Update()
	{
		if (!isBusy && urls.Count > 0) {
		
			DLData d = urls [0];
			urls.RemoveAt (0);

			StartCoroutine (BeginLoad(d));
		}
	}

	public static void Load( string url, Action<float> ProgressCallback, Action<WWW> FinishCallback, bool AutoSaveHttpRes, bool FindLocal = true )
	{
		if (FindLocal) {
			if (HaveDownload (url)) {
				if (IsHttpUrl (url))
					Load ( "file:///" + Url2LocalPath (url), ProgressCallback, FinishCallback, null);
				else
					Load (url, ProgressCallback, FinishCallback, null);

				return;
			}

		}
		
		if (AutoSaveHttpRes && IsHttpUrl (url))
			Load (url, ProgressCallback, FinishCallback, Url2LocalPath (url));
		else
			Load (url, ProgressCallback, FinishCallback, null);
	}

	// 下载接口
	public static void Load( string url, Action<float> ProgressCallback, Action<WWW> FinishCallback, string savePath)
	{
		DLData d = new DLData (url, ProgressCallback, FinishCallback, savePath);

		urls.Add (d);

	}


	private static bool isBusy = false;
	// 下载资源
	IEnumerator BeginLoad( DLData data )
	{
		isBusy = true;

		WWW www = new WWW(data.url);

		while (!www.isDone) {
		
			if ( data.progressCallback != null)
				data.progressCallback (www.progress);

			yield return new WaitForEndOfFrame ();

		}

		yield return www;


		if (www.error != null) {
			if (data.finishCallback != null)
				data.finishCallback (www);
		}
		else {

			if ( !string.IsNullOrEmpty( data.savePath ) )
				WriteToFile (data.savePath, www.bytes);

			if (data.finishCallback != null)
				data.finishCallback ( www );

		}

		isBusy = false;
	}

	public static bool WriteToFile( string path, byte[] bytes)
	{
		string dir = path.Substring (0, path.LastIndexOf ('/'));

		if (Directory.Exists (dir) == false)
			Directory.CreateDirectory (dir);

		File.WriteAllBytes (path, bytes);

		return true;
	}
		



}


